package example.blob;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.nhn.android.base.multipart.FilePart;
import com.nhn.android.base.multipart.MultipartEntity;
import com.nhn.android.base.multipart.Part;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.webkit.MimeTypeMap;

public class TestBlobAppActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		UploadAsyncTask task = new UploadAsyncTask();
		String[] path = new String[1];
		path[0] = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/Koala.jpg";

		task.execute(path[0]);

	}

	static public class UploadAsyncTask extends
			AsyncTask<String, Integer, Integer> {

		static public HttpClient createHttpClient() {
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));

			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
			HttpConnectionParams.setSoTimeout(params, 30 * 1000);
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

			ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(
					params, registry);

			HttpClient httpclient = new DefaultHttpClient(manager, params);
			return httpclient;
		}

		@Override
		protected Integer doInBackground(String... params) {

			HttpClient httpclient = createHttpClient();
			HttpPost httppost = new HttpPost(
					"http://superapps21.appspot.com/uploadurl");
			HttpResponse response;
			String uploadUrl = null;
			try {
				response = httpclient.execute(httppost);
				int responseCode = response.getStatusLine().getStatusCode();
				if (responseCode == HttpURLConnection.HTTP_OK) {
					Header[] headers = response.getHeaders("uploadUrl");
					for (int i = 0; i < headers.length; i++) {
						Header header = headers[i];
						if (header.getName().equals("uploadUrl"))
							uploadUrl = header.getValue();
					}
					Log.d("Test", "uploadUrl : " + uploadUrl);

					// HttpEntity resEntity = response.getEntity();
					// byte[] bytes = EntityUtils.toByteArray(resEntity);
					// uploadUrl = new String(bytes, "UTF-8");
					// Log.d("Test", "uploadUrl : " + uploadUrl);
					// uploadUrl = URLEncoder.encode(uploadUrl);
					// Log.d("Test", "uploadUrl : " + uploadUrl);
				}
			} catch (ClientProtocolException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return 0;
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return 0;
			}

			if (uploadUrl == null) {
				return 0;
			}

			httpclient = createHttpClient();
			httppost = new HttpPost(uploadUrl);
					
			ArrayList<Part> partArray = new ArrayList<Part>();

			FilePart filePart = null;
			try {
				filePart = new FilePart("attachment", new File(params[0]), getMimeTypeByFilename(params[0]), null);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return 0;
			}
			partArray.add(filePart);

			int count = partArray.size();
			Part[] parts = new Part[count];
			for (int i = 0; i < count; i++) {
				parts[i] = partArray.get(i);
			}
			MultipartEntity entity = new MultipartEntity(parts);
			httppost.setEntity(entity);

			// File file = new File(params[0]);
			// FileEntity entity = new FileEntity(file, "multipart/form-data");
			// httppost.setEntity(entity);

			try {
				response = httpclient.execute(httppost);
				int responseCode = response.getStatusLine().getStatusCode();
				Log.d("Test", "ResponseCode : " + responseCode);
				if (responseCode == HttpURLConnection.HTTP_OK) {
					HttpEntity resEntity = response.getEntity();
					byte[] bytes = EntityUtils.toByteArray(resEntity);
					String string = new String(bytes, "UTF-8");
					Log.d("Test", "Response : " + string);

				} else {

				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

	}
	
	
	public static String getMimeTypeByFilename(String fileName) {
		int dotPos = 0;
		dotPos = fileName.lastIndexOf('.');
		if (dotPos == -1) {
			return null;
		}
		String fileNamePart = fileName.substring(0, dotPos);
		String fileExtension = fileName.substring(dotPos + 1, fileName.length());

		String mimeType = null;
		if (fileExtension != null) {
			fileExtension = fileExtension.toLowerCase();
			MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
			mimeType = mimeTypeMap.getMimeTypeFromExtension(fileExtension);
		}
		return mimeType;
	}
}